<script setup>
import { computed, getCurrentInstance, onMounted } from 'vue'
import { useContactsStore, useUserStore } from '@/stores/counter'
import defaultAvatar from '@/assets/svg/robot.svg'
import { RecycleScroller } from 'vue3-virtual-scroller'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { agreeAddFried } from '@/api/contacts'

const useContacts = useContactsStore()
const userStore = useUserStore()

// 使用 computed 将 newFriends 和 useContacts.applyList 关联
const newFriends = computed(() => useContacts.applyList)

onMounted(() => {
  // 获取新的朋友数据
  useContacts.getApplyList(userStore.userId)
})

// 获取 WebSocket 实例
const { appContext } = getCurrentInstance()
const ws = appContext.config.globalProperties.$wsApi

// 监听路由离开事件
const router = useRouter()

const acceptFriend = async (applyId) => {
  // 处理同意好友申请的逻辑
  const res = await agreeAddFried(applyId)
  ElMessage.success('已同意好友申请')
}

router.beforeEach((to, from, next) => {
  if (from.fullPath === '/newFriend') {
    // 发送 WebSocket 消息，通知后端用户已查看所有未阅读的好友申请信息
    const list = useContacts.applyList.map(item => item.applyId)
    const message = {
      type: 10001,
      data: {
        uid: userStore.userId,
        idList: list
      }
    }
    ws.sendMessage(message)
  }
  next()
})
</script>

<template>
  <div class="new-friends">
    <h1>新的朋友</h1>
    <RecycleScroller :items="newFriends" :item-size="185" key-field="applyId">
      <template #default="{ item: friend }">
        <div class="friend-div">
          <div class="friend-item">
            <img :src="friend.avatar || defaultAvatar" alt="Avatar" class="avatar" />
            <div class="friend-info">
              <div class="friend-name">{{ friend.userName }}</div>
              <div class="friend-msg">{{ friend.msg }}</div>
            </div>
            <div class="friend-actions">
              <div v-if="friend.status == 1">
                <el-button class="action-button" type="primary" @click="acceptFriend(friend.applyId)">同意</el-button>
              </div>
              <div v-else>
                <el-button disabled class="disabled-button">已同意</el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
    </RecycleScroller>
  </div>
</template>

<style lang="scss" scoped>
.new-friends {
  padding: 20px;
  width: 100%;
}

.friend-div {
  width: 100%;
  padding: 0 50px;
}

.friend-item {
  display: flex;
  align-items: center;
  height: 120px; /* 确保每个列表项有足够的高度 */
  border-bottom: 1px solid rgb(181, 177, 177); /* 设置下边框 */
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 20px;
}

.friend-info {
  flex-grow: 1;
}

.friend-name {
  font-weight: bold;
}

.friend-msg {
  color: #888;
  margin-top: 5px;
}

.friend-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.disabled-button,
.action-button {
  width: 100px; /* 设置按钮的宽度 */
}
</style>